package cn.iocoder.ny.module.mall.controller.admin.manage;

import cn.iocoder.ny.module.mall.annotation.Decrypt;
import cn.iocoder.ny.module.mall.annotation.Encrypt;
import cn.iocoder.ny.module.mall.controller.admin.manage.vo.StaffUserVo;
import cn.iocoder.ny.module.mall.domain.MallOrder;
import cn.iocoder.ny.module.mall.service.IMallOrderService;
import cn.iocoder.ny.module.mall.service.IMallQRCodeService;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.dal.dataobject.saas.dto.StaffBindDto;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.SystemUserVo;
import cn.iocoder.yudao.module.system.dal.dataobject.system.SystemUsers;
import cn.iocoder.yudao.module.system.service.system.ISystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;

/**
 * @author luchunhong
 * @date 2024/10/23/ 9:42
 * @description:
 */
// 员工管理
// 功能:绑定该用户为核销员+操作员+商品核销+二维码生成
@RestController
@RequestMapping("staffManagement")
public class StaffManagementController {

    @Autowired
    private IMallQRCodeService qrCodeService;
    @Resource
    private ISystemUserService systemUserService;
    @Autowired
    private IMallOrderService mallOrderService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;




    /**
     * 通过手机号查询当前店铺的用户信息
     */

    @PostMapping("queryUserByMobile")
//    @Encrypt
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult<Map<Object,Object>> queryUserByMobile(@RequestBody SystemUsers systemUsers) {
        Long tenantId = getLoginUser().getTenantId();
        SystemUserVo userByMobile = systemUserService.getUserByMobile(systemUsers.getMobile());
        Map<Object, Object> userMap = new HashMap<>();
        if(userByMobile != null){
            userMap.put("nickName",userByMobile.getNickname());
            userMap.put("mobile",userByMobile.getMobile());
            userMap.put("avatar",userByMobile.getAvatar());
            userMap.put("userId",userByMobile.getId());
            userMap.put("tenantId",tenantId);
            userMap.put("roleCodes",userByMobile.getRoleCodes());
            userMap.put("roleNames",userByMobile.getRoleNames());
            return CommonResult.success(userMap);
        }
        return CommonResult.error(500,"null");
    }
    /**
     * 核销员/操作员绑定
     */
    @PostMapping("bindStaff")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult<String> bindStaff(@RequestBody StaffBindDto staffBindDto) {
        boolean b = systemUserService.bindStaff(staffBindDto);
        if (!b){
            return CommonResult.error(500,"绑定失败");
        }
        return CommonResult.success("绑定成功");
    }
    /**
     * 查询当前店铺下的核销员/操作员
     */
    @PostMapping("getStaffListByTenantId")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin')")
    public CommonResult<List<SystemUserVo>> getStaffList(@RequestBody StaffUserVo staffUserVo) {
        List<SystemUserVo> userListByTenantId = systemUserService.getUserListByTenantId(staffUserVo.getTenantId(),staffUserVo.getRoleCode());
        return CommonResult.success(userListByTenantId);
    }


    /**
     * 商品核销回调
     * @param requestBody
     * @return
     */
    @PostMapping("protectedReturn")
    @PermitAll
    public CommonResult<String> protectedReturn(@RequestBody Map<String, Object> requestBody){
        if (!ObjectUtils.isEmpty(requestBody.get("orderId"))){
            Boolean orderid = redisTemplate.delete("staffOrder" + requestBody.get("orderId"));
            if (orderid){
                return CommonResult.success("核销成功");
            }
        }
        return CommonResult.error(500,null);
    }

    /**
     * 商品核销接口
     * @param
     * @param response
     * @throws IOException
     */
    @PostMapping("protectedResource")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin','mall_verification')")
    public CommonResult<String> handleScan(@RequestBody Map<String, Object> requestBody, HttpServletResponse response) throws IOException {
        List<String> identities = (List<String>) requestBody.get("roles");
        Long tenantId = getLoginUser().getTenantId();
        // 使用集合来定义允许的身份
        Set<String> allowedRoles = new HashSet<>(Arrays.asList("merchant_admin", "mall_verification", "super_admin"));
        boolean isAuthorized = identities.stream().anyMatch(allowedRoles::contains);
        if (isAuthorized) {
            // 修改订单的状态为已核销
            boolean update = mallOrderService.lambdaUpdate()
                    .eq(MallOrder::getTenantId, tenantId)
                    .eq(MallOrder::getId, requestBody.get("orderId"))
                    .and(wrapper -> wrapper.eq(MallOrder::getStatus, 1).or().eq(MallOrder::getStatus, 5))
                    .eq(MallOrder::getDelFlag, 0)
                    .set(MallOrder::getStatus, 2)
                    //绑定核销员ID
                    .set(MallOrder::getVerificationUserId, getLoginUser().getId())
                    .update();
            if (!update) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//                response.getWriter().write("{\"message\": \"核销失败\"}");
                return CommonResult.error(500,"核销失败");
            }
//            response.getWriter().write("{\"message\": \"核销成功\"}");
            redisTemplate.opsForValue().set("staffOrder"+requestBody.get("orderId"),requestBody.get("orderId"));
            return CommonResult.success("核销成功");
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//            response.getWriter().write("{\"message\": \"您当前没有权限进行核销\"}");
            return CommonResult.error(500,"您当前没有权限进行核销");

        }
    }



    /**
     * 生成核销码
     * @param response
     * @throws IOException
     */
    @PostMapping("makeerByOrderId")
    // 允许所有用户生成二维码
    @PermitAll
    public void makeer(@RequestBody MallOrder mallOrder, HttpServletResponse response) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 生成二维码内容
        Long content = generateQrCodeContent(response, mallOrder.getId());
        content = content;
        // 生成二维码
        qrCodeService.generateStream(String.valueOf(content), baos);
        byte[] qrCodeBytes = baos.toByteArray();
        String base64QRCode = Base64.getEncoder().encodeToString(qrCodeBytes);
        response.setContentType("application/json");
        response.getWriter().write("{\"qrCode\": \"" + base64QRCode + "\"}");
    }

    private Long generateQrCodeContent(HttpServletResponse response, Long orderId) throws IOException {
        return orderId;
    }
    private boolean isAuthorizedUser(String userId) {
        return "mallUser".equals(userId);
    }
}
